<?php
namespace utils;
use \think\Facade\Cache;
class RedisQueue
{
    private $queueName = 'xcx_queue';
    private $cache;
    private $sid;
    function __construct($domain,$sid){
         $this->cache = Cache::store('redis')->handler();
         $this->sid = $sid;
    }
    public function set(array $data = []){
        if ( empty($data) ){
            throw new \Exception('数据不能为空');
        }
        $data['sid'] = $this->sid;
        return $this->cache->rpush($this->queueName,json_encode($data));
    }
    public function get(int $index = 0){
        $data = $this->cache->lindex($this->queueName,$index);
        if ( $data ){
            return json_decode($data,true);
        }
        return false;
    }
    public function getAll(){
        $list = [];
        for($i = 0; $i < $this->cache->llen($this->queueName); $i++){
            $queue = $this->cache->lindex($this->queueName,$i);
            $queue = json_decode($queue,true);
            $list[] = $queue;
        }
        return $list;
    }
    /**
     * 当前企业在队列中的名次
     */
    public function getRank(){
        $list = -1;
        for($i = 0; $i < $this->cache->llen($this->queueName); $i++){
            $queue = $this->cache->lindex($this->queueName,$i);
            $queue = json_decode($queue,true);
            if( (time() - $queue['time'] ) > config('app.queueTimeout') ){
                $this->remove($i);
            }
            if ( isset($queue['sid']) &&  $queue['sid'] == $this->sid ){
                $list = $i;
                if ( $i > 0 ){
                    $queue['time'] = time();
                    $this->cache->lset($this->queueName,$i,json_encode($queue));
                }
               
                break;
            }
        }
        return $list;
    }
    /**
     * 获取排队总人数
     */
    public function getTotal(){
        return $this->cache->llen($this->queueName);
    }
    /**
     * 设置当前操作的企业
     */
    public function setCurrent($enterprice_id){
        return  $this->cache->set('current_xcx',$enterprice_id);
    }
    /**
     * 完成，删除第一个
     */
    public function finish(){
        $index = $this->getRank();
        $data = $this->get($index);
        return $this->cache->lrem($this->queueName,json_encode($data),$index);
    }

    public function remove($index){
        $data = $this->get($index);
        return $this->cache->lrem($this->queueName,json_encode($data),$index);
    }
}
?>